# -*- coding: utf-8 -*-
"""
订单控制层

负责处理订单相关的HTTP请求和响应，包括客户下单、代理下单、订单查询等
"""
from fastapi import APIRouter, HTTPException, Depends, Query, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from pydantic import BaseModel, Field
from typing import Optional, List, Dict, Any, Union
from datetime import datetime
import json
from app.services.cart_service import OrderService
from app.services.role_service import OrderService as ProxyOrderService
from app.controllers.user_controller import get_current_user

# 创建路由
order_router = APIRouter(
    prefix="/orders",
    tags=["orders"],
    responses={404: {"description": "Not found"}}
)

# 创建兼容路由器（用于向后兼容）
compat_order_router = APIRouter(
    prefix="/compat/orders",
    tags=["compat-orders"],
    responses={404: {"description": "Not found"}}
)

# HTTP Bearer token scheme
security = HTTPBearer()

# 初始化服务层
order_service = OrderService()
proxy_order_service = ProxyOrderService()

# 基于前端数据结构的Pydantic模型
class AddressModel(BaseModel):
    id: int = Field(..., description="地址ID")
    name: str = Field(..., description="收货人姓名")
    phone: str = Field(..., description="收货人电话")
    address: str = Field(..., description="详细地址")
    isDefault: bool = Field(False, description="是否为默认地址")

class PaymentMethodModel(BaseModel):
    id: str = Field(..., description="支付方式ID")
    name: str = Field(..., description="支付方式名称")
    desc: str = Field(..., description="支付方式描述")
    icon: str = Field(..., description="支付方式图标")
    color: str = Field(..., description="支付方式颜色")
    type: str = Field(..., description="支付类型")

class PaymentModel(BaseModel):
    method: PaymentMethodModel = Field(..., description="支付方式详情")
    type: str = Field(..., description="支付类型")

class DeliveryModel(BaseModel):
    method: Optional[str] = Field("standard", description="配送方式")
    time: Optional[str] = Field(None, description="配送时间")
    fee: Optional[float] = Field(0, description="配送费用")

class GoodsModel(BaseModel):
    id: str = Field(..., description="商品ID")
    goodsId: str = Field(..., description="商品ID")
    name: str = Field(..., description="商品名称")
    image: str = Field(..., description="商品图片")
    price: float = Field(..., description="商品价格")
    quantity: int = Field(..., description="商品数量")
    spec: Optional[str] = Field(None, description="商品规格")
    specId: Optional[str] = Field(None, description="规格ID")
    specName: Optional[str] = Field(None, description="规格名称")
    badge: Optional[str] = Field(None, description="商品标签")

class CreateOrderRequestV2(BaseModel):
    """基于前端数据结构的下单请求"""
    address: AddressModel = Field(..., description="收货地址信息")
    goods: List[GoodsModel] = Field(..., description="商品列表")
    payment: PaymentModel = Field(..., description="支付信息")
    delivery: Optional[DeliveryModel] = Field(None, description="配送信息")
    deliveryFee: float = Field(0, description="配送费用")
    goodsTotal: float = Field(..., description="商品总价")
    totalPrice: float = Field(..., description="订单总价")
    remark: Optional[str] = Field("", description="订单备注")
    type: str = Field("buy", description="订单类型")
    coupon: Optional[Dict[str, Any]] = Field(None, description="优惠券信息")

class OrderConfirmRequest(BaseModel):
    """订单确认请求"""
    goods_ids: List[str] = Field(..., description="商品ID列表")
    address_id: Optional[int] = Field(None, description="地址ID")
    coupon_id: Optional[str] = Field(None, description="优惠券ID")

class OrderSubmitRequest(BaseModel):
    """订单提交请求"""
    order_data: CreateOrderRequestV2 = Field(..., description="订单数据")

# 原有的Pydantic模型保持不变
class CreateOrderRequest(BaseModel):
    address_id: Optional[str] = Field(None, description="收货地址ID，不传则使用默认地址")
    payment_method: Optional[str] = Field(None, description="支付方式")
    shipping_fee: Optional[float] = Field(0, description="运费")
    discount_amount: Optional[float] = Field(0, description="优惠金额")
    notes: Optional[str] = Field("", description="订单备注")

class ProxyOrderRequest(BaseModel):
    customer_id: str = Field(..., description="客户ID")
    items: List[Dict[str, Any]] = Field(..., description="订单商品列表")
    total_amount: float = Field(..., description="订单总金额")
    discount_amount: Optional[float] = Field(0, description="优惠金额")
    shipping_fee: Optional[float] = Field(0, description="运费")
    final_amount: float = Field(..., description="最终金额")
    payment_method: Optional[str] = Field(None, description="支付方式")
    shipping_address: Optional[str] = Field(None, description="收货地址")
    notes: Optional[str] = Field(None, description="订单备注")

class UpdateOrderStatusRequest(BaseModel):
    order_status: str = Field(..., description="订单状态")
    notes: Optional[str] = Field(None, description="状态变更备注")

class OrderQueryRequest(BaseModel):
    order_status: Optional[str] = Field(None, description="订单状态筛选")
    customer_id: Optional[str] = Field(None, description="客户ID筛选")
    date_from: Optional[str] = Field(None, description="开始日期")
    date_to: Optional[str] = Field(None, description="结束日期")
    page: int = Field(1, gt=0, description="页码")
    page_size: int = Field(10, gt=0, le=100, description="每页数量")

class CreateOrderFromCartRequest(BaseModel):
    cart_ids: List[int] = Field(..., description="购物车商品ID列表")
    address_id: int = Field(..., description="收货地址ID")
    payment_method: Optional[str] = Field("wechat", description="支付方式")
    shipping_fee: Optional[float] = Field(0, description="运费")
    discount_amount: Optional[float] = Field(0, description="优惠金额")
    notes: Optional[str] = Field("", description="订单备注")

class CreateDirectOrderRequest(BaseModel):
    goods_items: List[Dict[str, Any]] = Field(..., description="商品列表")
    address_id: int = Field(..., description="收货地址ID")
    payment_method: Optional[str] = Field("wechat", description="支付方式")
    shipping_fee: Optional[float] = Field(0, description="运费")
    discount_amount: Optional[float] = Field(0, description="优惠金额")
    notes: Optional[str] = Field("", description="订单备注")

class GoodsOrderItem(BaseModel):
    goods_id: int = Field(..., description="商品ID")
    goods_spec_id: Optional[int] = Field(None, description="商品规格ID")
    quantity: int = Field(..., gt=0, description="购买数量")
    price: Optional[float] = Field(None, description="商品价格（可选，不传则使用商品表价格）")

# 在OrderSubmitRequest类后面添加新的模型定义

class FrontendOrderRequest(BaseModel):
    """前端直接发送的订单数据结构"""
    order_type: str = Field(..., description="订单类型")
    address_id: int = Field(..., description="地址ID")
    delivery_type: int = Field(..., description="配送类型")
    delivery_fee: float = Field(0, description="配送费用")
    payment_type: str = Field(..., description="支付类型")
    payment_method: str = Field(..., description="支付方式")
    goods_list: List[Dict[str, Any]] = Field(..., description="商品列表")
    goods_total: float = Field(..., description="商品总价")
    total_price: float = Field(..., description="订单总价")
    delivery_detail: Optional[Dict[str, Any]] = Field(None, description="配送详情")
    delivery_info: Optional[Dict[str, Any]] = Field(None, description="配送信息")
    coupon_id: Optional[str] = Field(None, description="优惠券ID")
    remark: Optional[str] = Field("", description="订单备注")

# =========================== 旺店通数据模型 ===========================

class WdtOrderModel(BaseModel):
    """旺店通订单明细模型"""
    oid: str = Field(..., description="订单明细ID")
    num: int = Field(..., description="商品数量")
    price: float = Field(..., description="商品单价")
    status: int = Field(30, description="订单状态，30表示待发货")
    refund_status: int = Field(0, description="退款状态，0表示无退款")
    goods_id: str = Field(..., description="商品ID")
    spec_id: str = Field(..., description="规格ID")
    goods_no: str = Field(..., description="商品编号")
    spec_no: str = Field(..., description="规格编号")
    goods_name: str = Field(..., description="商品名称")
    discount: float = Field(0, description="优惠金额")
    adjust_amount: float = Field(0, description="调整金额")
    share_discount: float = Field(0, description="分摊优惠")

class WdtTradeModel(BaseModel):
    """旺店通交易主单模型"""
    tid: str = Field(..., description="交易单号")
    trade_status: int = Field(20, description="交易状态，20表示已付款")
    pay_status: str = Field("1", description="支付状态，1表示已支付")
    delivery_term: int = Field(2, description="发货期限")
    trade_time: str = Field(..., description="交易时间")
    buyer_nick: str = Field(..., description="买家昵称")
    receiver_name: str = Field(..., description="收货人姓名")
    receiver_province: str = Field(..., description="收货省份")
    receiver_city: str = Field(..., description="收货城市")
    receiver_district: str = Field(..., description="收货区县")
    receiver_address: str = Field(..., description="收货详细地址")
    logistics_type: int = Field(4, description="物流类型")
    post_amount: float = Field(..., description="邮费")
    cod_amount: float = Field(0, description="货到付款金额")
    ext_cod_fee: float = Field(0, description="货到付款手续费")
    other_amount: float = Field(0, description="其他费用")
    paid: float = Field(0, description="已支付金额")
    order_list: List[WdtOrderModel] = Field(..., description="订单明细列表")

class WdtTradeListRequest(BaseModel):
    """旺店通交易推送请求"""
    shop_no: str = Field(..., description="店铺编号")
    trade_list: List[WdtTradeModel] = Field(..., description="交易列表")

class GenerateWdtDataRequest(BaseModel):
    """生成旺店通数据请求"""
    trade_no: str = Field(..., description="本系统交易单号")
    shop_no: str = Field("test111", description="店铺编号")



# =========================== 销售员代理下单接口 ===========================

@order_router.post("/proxy")
async def create_proxy_order(request: ProxyOrderRequest, current_user = Depends(get_current_user)):
    """销售员代理下单"""
    try:
        salesman_id = current_user.get('user_id')
        user_role = current_user.get('user_role', 'customer')
        
        # 检查权限
        if user_role != 'salesman':
            raise HTTPException(status_code=403, detail="只有销售员可以代理下单")
        
        order_data = request.dict()
        result = proxy_order_service.create_proxy_order(salesman_id, order_data)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except PermissionError as e:
        raise HTTPException(status_code=403, detail=str(e))
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"代理下单失败: {str(e)}")


# =========================== 订单管理接口（管理员/销售员） ===========================

@order_router.get("/manage/list")
async def get_orders_for_management(
    customer_id: Optional[str] = Query(None, description="客户ID筛选"),
    order_status: Optional[str] = Query(None, description="订单状态筛选"),
    salesman_id: Optional[str] = Query(None, description="销售员ID筛选"),
    date_from: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"),
    date_to: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(10, gt=0, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取订单管理列表（管理员/销售员）"""
    try:
        user_role = current_user.get('user_role', 'customer')
        user_id = current_user.get('user_id')
        
        # 权限检查
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        # 如果是销售员，只能查看自己服务的客户订单
        if user_role == 'salesman':
            salesman_id = user_id
        
        query_params = {
            'customer_id': customer_id,
            'order_status': order_status,
            'salesman_id': salesman_id,
            'date_from': date_from,
            'date_to': date_to,
            'page': page,
            'page_size': page_size
        }
        
        result = order_service.get_orders_for_management(query_params)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单列表失败: {str(e)}")


@order_router.put("/{order_id}/status")
async def update_order_status(
    order_id: str,
    request: UpdateOrderStatusRequest,
    current_user = Depends(get_current_user)
):
    """更新订单状态"""
    try:
        user_role = current_user.get('user_role', 'customer')
        user_id = current_user.get('user_id')
        
        # 权限检查
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        result = order_service.update_order_status(
            order_id, 
            request.order_status, 
            user_id, 
            request.notes
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新订单状态失败: {str(e)}")


# =========================== 订单统计接口 ===========================

@order_router.get("/statistics/summary")
async def get_order_statistics(
    date_from: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"),
    date_to: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"),
    current_user = Depends(get_current_user)
):
    """获取订单统计信息"""
    try:
        user_role = current_user.get('user_role', 'customer')
        user_id = current_user.get('user_id')
        
        # 权限检查
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        # 如果是销售员，只统计自己的数据
        salesman_id = user_id if user_role == 'salesman' else None
        
        result = order_service.get_order_statistics(date_from, date_to, salesman_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单统计失败: {str(e)}")


@order_router.get("/statistics/trends")
async def get_order_trends(
    days: int = Query(30, ge=1, le=365, description="统计天数"),
    current_user = Depends(get_current_user)
):
    """获取订单趋势统计"""
    try:
        user_role = current_user.get('user_role', 'customer')
        user_id = current_user.get('user_id')
        
        # 权限检查
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        # 如果是销售员，只统计自己的数据
        salesman_id = user_id if user_role == 'salesman' else None
        
        result = order_service.get_order_trends(days, salesman_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单趋势失败: {str(e)}")


# =========================== 订单导出接口 ===========================

@order_router.get("/export")
async def export_orders(
    customer_id: Optional[str] = Query(None, description="客户ID筛选"),
    order_status: Optional[str] = Query(None, description="订单状态筛选"),
    date_from: Optional[str] = Query(None, description="开始日期 YYYY-MM-DD"),
    date_to: Optional[str] = Query(None, description="结束日期 YYYY-MM-DD"),
    format: str = Query("excel", description="导出格式: excel, csv"),
    current_user = Depends(get_current_user)
):
    """导出订单数据"""
    try:
        user_role = current_user.get('user_role', 'customer')
        user_id = current_user.get('user_id')
        
        # 权限检查
        if user_role not in ['admin', 'salesman']:
            raise HTTPException(status_code=403, detail="权限不足")
        
        # 如果是销售员，只能导出自己服务的客户订单
        salesman_id = user_id if user_role == 'salesman' else None
        
        query_params = {
            'customer_id': customer_id,
            'order_status': order_status,
            'salesman_id': salesman_id,
            'date_from': date_from,
            'date_to': date_to,
            'format': format
        }
        
        result = order_service.export_orders(query_params)
        
        if result['success']:
            return {
                "code": 200,
                "message": "导出成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"导出订单失败: {str(e)}")

# =========================== 新增接口：基于前端数据结构 ===========================

@order_router.post("/confirm")
async def confirm_order_info(request: OrderConfirmRequest, current_user = Depends(get_current_user)):
    """订单确认页面 - 获取订单预览信息"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.confirm_order_info(
            user_id=user_id,
            goods_ids=request.goods_ids,
            address_id=request.address_id,
            coupon_id=request.coupon_id
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取订单确认信息成功",
                "data": {
                    "address": result['data']['address'],
                    "goods": result['data']['goods'],
                    "payment": {
                        "method": {
                            "id": "wechat",
                            "name": "微信支付",
                            "desc": "安全便捷，推荐使用",
                            "icon": "weixin",
                            "color": "#07C160",
                            "type": "online"
                        },
                        "type": "online"
                    },
                    "delivery": result['data']['delivery'],
                    "deliveryFee": result['data']['delivery_fee'],
                    "goodsTotal": result['data']['goods_total'],
                    "totalPrice": result['data']['total_price'],
                    "coupon": result['data']['coupon'],
                    "availableCoupons": result['data']['available_coupons']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单确认信息失败: {str(e)}")

@order_router.post("/submit")
async def submit_order(request: Request, current_user = Depends(get_current_user)):
    """提交订单（支持多种数据格式）"""
    try:
        user_id = current_user.get('user_id')
        
        # 获取原始请求体
        raw_body = await request.body()
        request_data = json.loads(raw_body.decode('utf-8'))
        
        # 检测数据格式
        if 'order_data' in request_data:
            # 原有格式：{"order_data": {...}}
            order_data = request_data['order_data']
            
            # 转换为service层期望的格式
            converted_order_data = {
                'goods': order_data.get('goods', []),
                'deliveryFee': order_data.get('deliveryFee', 0),
                'totalPrice': order_data.get('totalPrice', 0),
                'goodsTotal': order_data.get('goodsTotal', 0),
                'remark': order_data.get('remark', ''),
                'address': order_data.get('address', {}),
                'payment': order_data.get('payment', {})
            }
            
        else:
            # 前端直接格式
            # 将前端数据转换为service层期望的格式
            
            # 处理支付方式
            payment_method = request_data.get('payment_method', 'wechat')
            if isinstance(payment_method, dict):
                payment_type = payment_method.get('type', 'wechat')
            else:
                payment_type = payment_method
            
            converted_order_data = {
                'goods': [],
                'deliveryFee': request_data.get('shipping_fee', request_data.get('delivery_fee', 0)),
                'totalPrice': request_data.get('total_amount', request_data.get('total_price', 0)),
                'goodsTotal': request_data.get('goods_total', 0),
                'remark': request_data.get('remark', ''),
                'address': {
                    'id': request_data.get('address_id'),
                    'name': request_data.get('delivery_info', {}).get('receiver_name', ''),
                    'phone': request_data.get('delivery_info', {}).get('receiver_phone', ''),
                    'address': request_data.get('delivery_info', {}).get('receiver_address', ''),
                },
                'payment': {
                    'method': {
                        'type': payment_type
                    }
                }
            }
            
            # 转换商品列表格式
            for goods_item in request_data.get('goods_list', []):
                converted_order_data['goods'].append({
                    'goodsId': goods_item.get('goods_id'),
                    'name': goods_item.get('goods_name', '商品'),
                    'image': goods_item.get('goods_image', ''),
                    'price': goods_item.get('price', 0),
                    'quantity': goods_item.get('quantity', 1),
                    'spec': goods_item.get('spec', '默认规格'),
                    'specId': goods_item.get('spec_id', 'default'),
                    'specName': goods_item.get('spec_name', '默认规格')
                })
        
        result = order_service.submit_order(
            user_id=user_id,
            order_data=converted_order_data
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "订单提交成功",
                "data": {
                    "order_id": result['data']['order_id'],
                    "trade_no": result['data']['trade_no'],
                    "total_amount": result['data']['total_amount'],
                    "goods_amount": result['data']['goods_amount'],
                    "delivery_fee": result['data']['delivery_fee'],
                    "payment_method": result['data']['payment_method'],
                    "payment_info": result['data']['payment_info'],
                    "create_time": result['data']['create_time'],
                    "status": "pending_payment",
                    "database_info": result['data'].get('database_info', {})
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except json.JSONDecodeError:
        raise HTTPException(status_code=400, detail="请求数据格式错误")
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"订单提交失败: {str(e)}")

@order_router.get("/detail/{order_id}")
async def get_order_detail_v2(order_id: str, current_user = Depends(get_current_user)):
    """获取订单详情 - 包含完整的前端数据结构"""
    try:
        user_id = current_user.get('user_id')
        result = order_service.get_order_detail_v2(order_id, user_id)
        
        if result['success']:
            order_data = result['data']
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "orderId": order_data['order_id'],
                    "tradeNo": order_data['trade_no'],
                    "address": order_data['address'],
                    "goods": order_data['goods'],
                    "payment": order_data['payment'],
                    "delivery": order_data['delivery'],
                    "deliveryFee": order_data['delivery_fee'],
                    "goodsTotal": order_data['goods_total'],
                    "totalPrice": order_data['total_price'],
                    "paymentStatus": order_data['payment_status'],
                    "orderStatus": order_data['order_status'],
                    "remark": order_data['remark'],
                    "createTime": order_data['create_time'],
                    "payTime": order_data['pay_time'],
                    "type": order_data['type'],
                    "coupon": order_data['coupon']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单详情失败: {str(e)}")


@order_router.get("/list")
async def get_order_list(
    status: Optional[str] = Query(None, description="订单状态筛选"),
    payment_status: Optional[str] = Query(None, description="支付状态筛选"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(10, gt=0, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取订单列表 - 前端格式"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.get_order_list(
            user_id=user_id,
            status=status,
            payment_status=payment_status,
            page=page,
            page_size=page_size
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取订单列表成功",
                "data": result
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单列表失败: {str(e)}")


@order_router.post("/{order_id}/payment")
async def process_payment(order_id: str, current_user = Depends(get_current_user)):
    """处理订单支付"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.process_payment(order_id, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "支付处理成功",
                "data": {
                    "payment_url": result['data']['payment_url'],
                    "payment_params": result['data']['payment_params'],
                    "expires_at": result['data']['expires_at']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"支付处理失败: {str(e)}")


@order_router.get("/{order_id}/status")
async def get_order_status(order_id: str, current_user = Depends(get_current_user)):
    """获取订单状态"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.get_order_status(order_id, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "order_id": order_id,
                    "order_status": result['data']['order_status'],
                    "payment_status": result['data']['payment_status'],
                    "shipping_status": result['data']['shipping_status'],
                    "update_time": result['data']['update_time']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单状态失败: {str(e)}")


# =========================== 新增接口：购物车相关 ===========================

class AddToCartRequest(BaseModel):
    goods_id: str = Field(..., description="商品ID")
    spec_id: Optional[str] = Field(None, description="规格ID")
    quantity: int = Field(1, description="数量")

class UpdateCartItemRequest(BaseModel):
    quantity: int = Field(..., gt=0, description="数量")

@order_router.post("/cart/add")
async def add_to_cart(request: AddToCartRequest, current_user = Depends(get_current_user)):
    """添加商品到购物车"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.add_to_cart(
            user_id=user_id,
            goods_id=request.goods_id,
            spec_id=request.spec_id,
            quantity=request.quantity
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "添加成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"添加购物车失败: {str(e)}")


@order_router.get("/cart")
async def get_cart_items(current_user = Depends(get_current_user)):
    """获取购物车商品列表"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.get_cart_items(user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": {
                    "items": result['data']['items'],
                    "total_count": result['data']['total_count'],
                    "total_price": result['data']['total_price']
                }
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取购物车失败: {str(e)}")


@order_router.put("/cart/{cart_id}")
async def update_cart_item(
    cart_id: int,
    request: UpdateCartItemRequest,
    current_user = Depends(get_current_user)
):
    """更新购物车商品数量"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.update_cart_item(
            user_id=user_id,
            cart_id=cart_id,
            quantity=request.quantity
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "更新成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"更新购物车失败: {str(e)}")


@order_router.delete("/cart/{cart_id}")
async def remove_cart_item(cart_id: int, current_user = Depends(get_current_user)):
    """删除购物车商品"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.remove_cart_item(user_id, cart_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "删除成功"
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"删除购物车商品失败: {str(e)}")


# =========================== 地址管理接口 ===========================

@order_router.get("/addresses")
async def get_user_addresses(current_user = Depends(get_current_user)):
    """获取用户地址列表"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.get_user_addresses(user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取地址列表失败: {str(e)}")


@order_router.get("/addresses/default")
async def get_default_address(current_user = Depends(get_current_user)):
    """获取默认地址"""
    try:
        user_id = current_user.get('user_id')
        
        result = order_service.get_default_address(user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取默认地址失败: {str(e)}")


# =========================== 支付相关接口 ===========================

@order_router.get("/payment/methods")
async def get_payment_methods(current_user = Depends(get_current_user)):
    """获取支付方式列表"""
    try:
        result = order_service.get_payment_methods()
        
        if result['success']:
            return {
                "code": 200,
                "message": "获取成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取支付方式失败: {str(e)}")


@order_router.post("/{order_id}/payment/callback")
async def payment_callback(order_id: str, request: Dict[str, Any]):
    """支付回调接口"""
    try:
        result = order_service.handle_payment_callback(order_id, request)
        
        if result['success']:
            return {
                "code": 200,
                "message": "处理成功"
            }
        else:
            return {
                "code": 400,
                "message": result['message']
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"处理支付回调失败: {str(e)}"
        }


# =========================== 测试接口（开发调试用） ===========================

@order_router.get("/detail-frontend/{order_id}")
async def get_order_detail_frontend(order_id: str, current_user = Depends(get_current_user)):
    """获取订单详情 - 完全匹配前端数据结构"""
    try:
        user_id = current_user.get('user_id')
        
        # 调用service层获取订单数据（这里用模拟数据）
        # 实际项目中应该调用: result = order_service.get_order_detail(order_id, user_id)
        
        # 模拟订单数据，完全匹配前端格式
        mock_order = {
            "orderNumber": order_id,
            "createTime": "2025-05-28 14:30:12",
            "paymentMethod": "线下付款",
            "deliveryMethod": "顺丰速运",
            "status": "completed",
            "receiverName": "张三",
            "receiverPhone": "13800138000",
            "receiverAddress": "北京市朝阳区建国路88号SOHO现代城B座1501",
            "goodsList": [
                {
                    "id": 1,
                    "name": "Apple iPhone 14 Pro 256GB 暗紫色",
                    "spec": "256GB/暗紫色",
                    "imageUrl": "/static/images/goods-iphone.jpg",
                    "price": 7999.00,
                    "quantity": 1
                },
                {
                    "id": 2,
                    "name": "Apple AirPods Pro 2代",
                    "spec": "无线充电盒",
                    "imageUrl": "/static/images/goods-airpods.jpg",
                    "price": 1899.00,
                    "quantity": 1
                }
            ],
            "goodsTotal": 9898.00,
            "shippingFee": 0.00,
            "couponAmount": 500.00,
            "totalAmount": 9398.00
        }
        
        return {
            "code": 200,
            "message": "获取订单详情成功",
            "data": {
                "order": mock_order
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单详情失败: {str(e)}")


@order_router.get("/detail-frontend-test/{order_id}")
async def get_order_detail_frontend_test(order_id: str):
    """获取订单详情测试接口 - 无需认证，匹配前端数据结构"""
    try:
        # 根据order_id返回不同的模拟数据
        if order_id == "20250528143012345678":
            mock_order = {
                "orderNumber": "20250528143012345678",
                "createTime": "2025-05-28 14:30:12",
                "paymentMethod": "线下付款",
                "deliveryMethod": "顺丰速运",
                "status": "completed",
                "receiverName": "张三",
                "receiverPhone": "13800138000",
                "receiverAddress": "北京市朝阳区建国路88号SOHO现代城B座1501",
                "goodsList": [
                    {
                        "id": 1,
                        "name": "Apple iPhone 14 Pro 256GB 暗紫色",
                        "spec": "256GB/暗紫色",
                        "imageUrl": "/static/images/goods-iphone.jpg",
                        "price": 7999.00,
                        "quantity": 1
                    },
                    {
                        "id": 2,
                        "name": "Apple AirPods Pro 2代",
                        "spec": "无线充电盒",
                        "imageUrl": "/static/images/goods-airpods.jpg",
                        "price": 1899.00,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 9898.00,
                "shippingFee": 0.00,
                "couponAmount": 500.00,
                "totalAmount": 9398.00
            }
        else:
            # 其他订单的模拟数据
            mock_order = {
                "orderNumber": order_id,
                "createTime": "2025-06-08 10:30:00",
                "paymentMethod": "微信支付",
                "deliveryMethod": "中通快递",
                "status": "pending_payment",
                "receiverName": "李四",
                "receiverPhone": "13900139000",
                "receiverAddress": "上海市浦东新区陆家嘴金融中心1号楼2001室",
                "goodsList": [
                    {
                        "id": 3,
                        "name": "银法利 6.875%氟菌霜霉威 悬浮剂",
                        "spec": "25 g/支 x 1支",
                        "imageUrl": "/static/images/goods-pesticide.jpg",
                        "price": 7.10,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 7.10,
                "shippingFee": 10.00,
                "couponAmount": 0.00,
                "totalAmount": 17.10
            }
        
        return {
            "code": 200,
            "message": "获取订单详情成功",
            "data": {
                "order": mock_order
            }
        }
        
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取订单详情失败: {str(e)}",
            "data": None
        }


@order_router.get("/detail-database/{trade_no}")
async def get_order_detail_from_database(trade_no: str, current_user = Depends(get_current_user)):
    """从数据库获取真实订单详情（基于trade_orders和trade_order_goods表）"""
    try:
        user_id = current_user.get('user_id')
        result = order_service.get_order_detail_from_database(trade_no, user_id)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 404,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取订单详情失败: {str(e)}",
            "data": None
        }


@order_router.get("/detail-database-test/{trade_no}")
async def get_order_detail_from_database_test(trade_no: str):
    """从数据库获取真实订单详情（测试版，无需认证）"""
    try:
        # 使用通用查询，不验证用户ID
        result = order_service.get_order_detail_from_database_without_user_check(trade_no)
        
        if result['success']:
            return {
                "code": 200,
                "message": result['message'],
                "data": result['data']
            }
        else:
            return {
                "code": 404,
                "message": result['message'],
                "data": None
            }
            
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取订单详情失败: {str(e)}",
            "data": None
        }


@order_router.get("/list-frontend")
async def get_order_list_frontend(
    status: Optional[str] = Query(None, description="订单状态筛选"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(10, gt=0, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取订单列表 - 匹配前端数据结构"""
    try:
        user_id = current_user.get('user_id')
        
        # 模拟订单列表数据，实际项目中应该调用service层
        mock_orders = [
            {
                "orderNumber": "20250528143012345678",
                "createTime": "2025-05-28 14:30:12",
                "paymentMethod": "线下付款",
                "deliveryMethod": "顺丰速运",
                "status": "completed",
                "receiverName": "张三",
                "receiverPhone": "13800138000",
                "receiverAddress": "北京市朝阳区建国路88号SOHO现代城B座1501",
                "goodsList": [
                    {
                        "id": 1,
                        "name": "Apple iPhone 14 Pro 256GB 暗紫色",
                        "spec": "256GB/暗紫色",
                        "imageUrl": "/static/images/goods-iphone.jpg",
                        "price": 7999.00,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 7999.00,
                "shippingFee": 0.00,
                "couponAmount": 500.00,
                "totalAmount": 7499.00
            },
            {
                "orderNumber": "ORD202506081050296974",
                "createTime": "2025-06-08 10:30:00",
                "paymentMethod": "微信支付",
                "deliveryMethod": "中通快递",
                "status": "pending_payment",
                "receiverName": "李四",
                "receiverPhone": "13900139000",
                "receiverAddress": "上海市浦东新区陆家嘴金融中心1号楼2001室",
                "goodsList": [
                    {
                        "id": 3,
                        "name": "银法利 6.875%氟菌霜霉威 悬浮剂",
                        "spec": "25 g/支 x 1支",
                        "imageUrl": "/static/images/goods-pesticide.jpg",
                        "price": 7.10,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 7.10,
                "shippingFee": 10.00,
                "couponAmount": 0.00,
                "totalAmount": 17.10
            }
        ]
        
        # 根据状态筛选
        if status:
            mock_orders = [order for order in mock_orders if order.get('status') == status]
        
        # 模拟分页
        total = len(mock_orders)
        start_idx = (page - 1) * page_size
        end_idx = start_idx + page_size
        paginated_orders = mock_orders[start_idx:end_idx]
        
        return {
            "code": 200,
            "message": "获取订单列表成功",
            "data": {
                "orders": paginated_orders,
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": (total + page_size - 1) // page_size
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单列表失败: {str(e)}")


@order_router.get("/list-frontend-test")
async def get_order_list_frontend_test(
    status: Optional[str] = Query(None, description="订单状态筛选"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(10, gt=0, le=100, description="每页数量")
):
    """获取订单列表测试接口 - 无需认证，匹配前端数据结构"""
    try:
        # 模拟订单列表数据
        mock_orders = [
            {
                "orderNumber": "20250528143012345678",
                "createTime": "2025-05-28 14:30:12",
                "paymentMethod": "线下付款",
                "deliveryMethod": "顺丰速运",
                "status": "completed",
                "receiverName": "张三",
                "receiverPhone": "13800138000",
                "receiverAddress": "北京市朝阳区建国路88号SOHO现代城B座1501",
                "goodsList": [
                    {
                        "id": 1,
                        "name": "Apple iPhone 14 Pro 256GB 暗紫色",
                        "spec": "256GB/暗紫色",
                        "imageUrl": "/static/images/goods-iphone.jpg",
                        "price": 7999.00,
                        "quantity": 1
                    },
                    {
                        "id": 2,
                        "name": "Apple AirPods Pro 2代",
                        "spec": "无线充电盒",
                        "imageUrl": "/static/images/goods-airpods.jpg",
                        "price": 1899.00,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 9898.00,
                "shippingFee": 0.00,
                "couponAmount": 500.00,
                "totalAmount": 9398.00
            },
            {
                "orderNumber": "ORD202506081050296974",
                "createTime": "2025-06-08 10:30:00",
                "paymentMethod": "微信支付",
                "deliveryMethod": "中通快递",
                "status": "pending_payment",
                "receiverName": "李四",
                "receiverPhone": "13900139000",
                "receiverAddress": "上海市浦东新区陆家嘴金融中心1号楼2001室",
                "goodsList": [
                    {
                        "id": 3,
                        "name": "银法利 6.875%氟菌霜霉威 悬浮剂",
                        "spec": "25 g/支 x 1支",
                        "imageUrl": "/static/images/goods-pesticide.jpg",
                        "price": 7.10,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 7.10,
                "shippingFee": 10.00,
                "couponAmount": 0.00,
                "totalAmount": 17.10
            },
            {
                "orderNumber": "TEST_ORDER_333",
                "createTime": "2025-06-07 16:15:30",
                "paymentMethod": "支付宝",
                "deliveryMethod": "京东快递",
                "status": "shipped",
                "receiverName": "王五",
                "receiverPhone": "13700137000",
                "receiverAddress": "深圳市南山区科技园南区高新南一道6号TCL大厦B座1005",
                "goodsList": [
                    {
                        "id": 4,
                        "name": "华为Mate 60 Pro 12GB+512GB 雅川青",
                        "spec": "12GB+512GB/雅川青",
                        "imageUrl": "/static/images/goods-huawei.jpg",
                        "price": 6999.00,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 6999.00,
                "shippingFee": 15.00,
                "couponAmount": 200.00,
                "totalAmount": 6814.00
            }
        ]
        
        # 根据状态筛选
        if status:
            mock_orders = [order for order in mock_orders if order.get('status') == status]
        
        # 模拟分页
        total = len(mock_orders)
        start_idx = (page - 1) * page_size
        end_idx = start_idx + page_size
        paginated_orders = mock_orders[start_idx:end_idx]
        
        return {
            "code": 200,
            "message": "获取订单列表成功",
            "data": {
                "orders": paginated_orders,
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": (total + page_size - 1) // page_size
            }
        }
        
    except Exception as e:
        return {
            "code": 500,
            "message": f"获取订单列表失败: {str(e)}",
            "data": None
        }


@order_router.get("/list-frontend")
async def get_order_list_frontend(
    status: Optional[str] = Query(None, description="订单状态筛选"),
    page: int = Query(1, gt=0, description="页码"),
    page_size: int = Query(10, gt=0, le=100, description="每页数量"),
    current_user = Depends(get_current_user)
):
    """获取订单列表 - 匹配前端数据结构"""
    try:
        user_id = current_user.get('user_id')
        
        # 模拟订单列表数据，实际项目中应该调用service层
        mock_orders = [
            {
                "orderNumber": "20250528143012345678",
                "createTime": "2025-05-28 14:30:12",
                "paymentMethod": "线下付款",
                "deliveryMethod": "顺丰速运",
                "status": "completed",
                "receiverName": "张三",
                "receiverPhone": "13800138000",
                "receiverAddress": "北京市朝阳区建国路88号SOHO现代城B座1501",
                "goodsList": [
                    {
                        "id": 1,
                        "name": "Apple iPhone 14 Pro 256GB 暗紫色",
                        "spec": "256GB/暗紫色",
                        "imageUrl": "/static/images/goods-iphone.jpg",
                        "price": 7999.00,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 7999.00,
                "shippingFee": 0.00,
                "couponAmount": 500.00,
                "totalAmount": 7499.00
            },
            {
                "orderNumber": "ORD202506081050296974",
                "createTime": "2025-06-08 10:30:00",
                "paymentMethod": "微信支付",
                "deliveryMethod": "中通快递",
                "status": "pending_payment",
                "receiverName": "李四",
                "receiverPhone": "13900139000",
                "receiverAddress": "上海市浦东新区陆家嘴金融中心1号楼2001室",
                "goodsList": [
                    {
                        "id": 3,
                        "name": "银法利 6.875%氟菌霜霉威 悬浮剂",
                        "spec": "25 g/支 x 1支",
                        "imageUrl": "/static/images/goods-pesticide.jpg",
                        "price": 7.10,
                        "quantity": 1
                    }
                ],
                "goodsTotal": 7.10,
                "shippingFee": 10.00,
                "couponAmount": 0.00,
                "totalAmount": 17.10
            }
        ]
        
        # 根据状态筛选
        if status:
            mock_orders = [order for order in mock_orders if order.get('status') == status]
        
        # 模拟分页
        total = len(mock_orders)
        start_idx = (page - 1) * page_size
        end_idx = start_idx + page_size
        paginated_orders = mock_orders[start_idx:end_idx]
        
        return {
            "code": 200,
            "message": "获取订单列表成功",
            "data": {
                "orders": paginated_orders,
                "total": total,
                "page": page,
                "page_size": page_size,
                "total_pages": (total + page_size - 1) // page_size
            }
        }
        
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取订单列表失败: {str(e)}")


# =========================== 旺店通数据生成接口 ===========================

@order_router.post("/generate-wdt-data")
async def generate_wdt_data(request: GenerateWdtDataRequest, current_user = Depends(get_current_user)):
    """根据订单生成旺店通格式数据并插入数据库"""
    try:
        result = order_service.generate_wdt_order_data(
            trade_no=request.trade_no,
            shop_no=request.shop_no,
            
            user_id=current_user.get('user_id')
        )
        
        if result['success']:
            return {
                "code": 200,
                "message": "旺店通数据生成成功",
                "data": result['data']
            }
        else:
            raise HTTPException(status_code=400, detail=result['message'])
            
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成旺店通数据失败: {str(e)}")

@order_router.post("/push-to-wdt")
async def push_to_wdt(request: WdtTradeListRequest):
    """模拟推送数据到旺店通接口（仅生成格式化数据）"""
    try:
        # 这里模拟旺店通接口调用的数据格式
        trade_list = []
        
        for trade in request.trade_list:
            order_list = []
            for order in trade.order_list:
                order_dict = {
                    "oid": order.oid,
                    "num": order.num,
                    "price": order.price,
                    "status": order.status,
                    "refund_status": order.refund_status,
                    "goods_id": order.goods_id,
                    "spec_id": order.spec_id,
                    "goods_no": order.goods_no,
                    "spec_no": order.spec_no,
                    "goods_name": order.goods_name,
                    "discount": order.discount,
                    "adjust_amount": order.adjust_amount,
                    "share_discount": order.share_discount
                }
                order_list.append(order_dict)
            
            trade_dict = {
                "tid": trade.tid,
                "trade_status": trade.trade_status,
                "pay_status": trade.pay_status,
                "delivery_term": trade.delivery_term,
                "trade_time": trade.trade_time,
                "buyer_nick": trade.buyer_nick,
                "receiver_name": trade.receiver_name,
                "receiver_province": trade.receiver_province,
                "receiver_city": trade.receiver_city,
                "receiver_district": trade.receiver_district,
                "receiver_address": trade.receiver_address,
                "logistics_type": trade.logistics_type,
                "post_amount": trade.post_amount,
                "cod_amount": trade.cod_amount,
                "ext_cod_fee": trade.ext_cod_fee,
                "other_amount": trade.other_amount,
                "paid": trade.paid,
                "order_list": order_list
            }
            trade_list.append(trade_dict)
        
        # 生成JSON格式的数据（与您的示例代码一致）
        json_data = json.dumps(trade_list, ensure_ascii=False)
        
        # 构造最终的参数结构
        params = {
            "shop_no": request.shop_no,
            "trade_list": json_data
        }
        
        return {
            "code": 200,
            "message": "旺店通数据格式生成成功",
            "data": {
                "formatted_params": params,
                "trade_count": len(trade_list),
                "order_count": sum(len(trade.order_list) for trade in request.trade_list)
            }
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"生成旺店通格式数据失败: {str(e)}")

@order_router.post("/create-wdt-sample")
async def create_wdt_sample_data():
    """创建旺店通示例数据（基于您提供的代码）"""
    try:
        # 构造示例订单数据
        order_1 = WdtOrderModel(
            oid='ghsTest121101',
            num=1,
            price=12,
            status=30,
            refund_status=0,
            goods_id='18344',
            spec_id='18656',
            goods_no='ghs2',
            spec_no='ghs201812070212123',
            goods_name='123',
            discount=0,
            adjust_amount=0,
            share_discount=0
        )
        
        # 构造示例交易数据
        trade_1 = WdtTradeModel(
            tid='AT201812110002',
            trade_status=20,
            pay_status='1',
            delivery_term=2,
            trade_time='2018-12-11 14:21:00',
            buyer_nick='三国杀',
            receiver_name='亚历山大',
            receiver_province='河南省',
            receiver_city='周口市',
            receiver_district='川汇区',
            receiver_address='123',
            logistics_type=4,
            post_amount=12,
            cod_amount=2,
            ext_cod_fee=0,
            other_amount=1,
            paid=0,
            order_list=[order_1]
        )
        
        # 构造请求数据
        wdt_request = WdtTradeListRequest(
            shop_no='test111',
            trade_list=[trade_1]
        )
        
        return {
            "code": 200,
            "message": "旺店通示例数据创建成功",
            "data": wdt_request.dict()
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"创建示例数据失败: {str(e)}") 